package com.code.zjm;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private TextView tvHint;
    private EditText etNumber;
    private Button btToSecond;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initVView();
        initListener();
    }

    public void initVView() {
        tvHint = (TextView) findViewById(R.id.tv_hint);
        etNumber = (EditText) findViewById(R.id.et_number);
        btToSecond = (Button) findViewById(R.id.bt_to_second);
    }

    public void initListener() {
        btToSecond.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String numberStr = etNumber.getText().toString();
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                Bundle bundle = new Bundle();
                if (numberStr.isEmpty()) {
                    Toast.makeText(MainActivity.this, "Input is not allow null!", Toast.LENGTH_SHORT).show();
                } else {
                    bundle.putInt("number", Integer.parseInt(numberStr));
                    intent.putExtras(bundle);
                    startActivityForResult(intent, 1);
                }
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Bundle bundle = data.getExtras();
        if (resultCode == 1) {
            tvHint.setText("You had access the SecondActivity " + bundle.getInt("numberResult") + " times");
        } else {
            tvHint.setText("The Result Code is not 1");
        }
    }
}
